package com.lagou.wwyan.rpc.server;

import com.lagou.wwyan.rpc.bean.RpcRequest;
import com.lagou.wwyan.rpc.bean.RpcResponse;
import com.lagou.wwyan.rpc.server.factory.RpcBeanFactory;
import com.lagou.wwyan.rpc.server.handler.RpcServerHandler;
import com.lagou.wwyan.rpc.sirealizer.JSONSerializer;
import com.lagou.wwyan.rpc.sirealizer.RpcDecoder;
import com.lagou.wwyan.rpc.sirealizer.RpcEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class RpcServer {
    private RpcBeanFactory beanFactory;

    public RpcServer(RpcBeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }

    public void startServer(String host, int port) throws InterruptedException {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        JSONSerializer serializer = new JSONSerializer();
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, serializer));
                        pipeline.addLast(new RpcEncoder(RpcResponse.class, serializer));
                        pipeline.addLast(new RpcServerHandler(beanFactory));
                    }
                });

        bootstrap.bind(port).sync();
    }
}
